package org.dizena.modules.master.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.dizena.base.avo.req.JqGridReq;
import org.dizena.base.avo.resp.JqGridResp;
import org.dizena.base.enums.State;
import org.dizena.base.shiro.SessionUserUtil;
import org.dizena.modules.master.bean.Role;
import org.dizena.modules.master.bean.User;
import org.dizena.modules.master.dao.RoleDao;
import org.dizena.modules.master.dao.UserDao;
import org.dizena.utils.IdGen;
import org.dizena.utils.JqGridRespBuilder;
import org.dizena.utils.ObjectUtil;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
@CacheConfig(cacheNames = "master:user")
public class UserService
{

    @Resource
    private UserDao userDao;
    @Resource
    private RoleDao roleDao;
    @Resource
    private JqGridRespBuilder<User> jqGridRespBuilder;

    public JqGridResp<User> list(JqGridReq req)
    {

        return jqGridRespBuilder.build(req, userDao);
    }

    public String crud(String oper, User user)
    {
        if ("add".equals(oper))
        {
            user.setId(IdGen.get().nextIdS());
            User old = userDao.queryAccount(user.getAccount());
            if (old != null)
            {
                return "account exist";
            }
            //默认密码 12345678
            String salt = ObjectUtil.makeNumberStr(8);
            String p1 = user.getPasswd() == null ? "12345678" : user.getPasswd();
            String passwd = DigestUtils.md5Hex(salt + p1);
            user.setPasswd(passwd);
            user.setSalt(salt);
            user.setCreateTime(System.currentTimeMillis());
            user.setUpdateTime(System.currentTimeMillis());
            userDao.add(user);
            return "ok";
        }
        else if ("edit".equals(oper))
        {
            user.setAccount(null);
            userDao.update(user);
            return "ok";
        }
        else if ("del".equals(oper))
        {
            String ids = user.getId();
            String[] ss = ids.split(",");
            Arrays.stream(ss).iterator().forEachRemaining(s ->
            {
                userDao.deleteById(s);
            });
            return "ok";
        }
        return "ok";
    }

    public String initData()
    {
        List<Role> roles = roleDao.queryAll(new JqGridReq(), null);
        String roleStr = "";
        for (Role role : roles)
        {
            roleStr += role.getRole() + ":" + role.getRole() + ";";
        }
        if (roleStr.endsWith(";"))
        {
            roleStr = roleStr.substring(0, roleStr.length() - 1);
        }
        return roleStr;
    }

    @Transactional(rollbackFor = Exception.class)
    public void lockUser(String id)
    {
        User user = userDao.get(id);
        User upUser = new User();
        upUser.setId(id);
        if (State.UNLOCK.getState().equals(user.getLocked()))
        {
            upUser.setLocked(State.LOCK.getState());
        }
        else
        {
            upUser.setLocked(State.UNLOCK.getState());
        }
        upUser.setUpdateTime(System.currentTimeMillis());
        userDao.update(upUser);
    }

    public void alterPassword(String id, String p1, String p2)
    {
        User upUser = new User();
        upUser.setId(id);
        String salt = ObjectUtil.makeNumberStr(8);
        String passwd = DigestUtils.md5Hex(salt + p1);
        upUser.setPasswd(passwd);
        upUser.setSalt(salt);
        upUser.setUpdateTime(System.currentTimeMillis());
        userDao.update(upUser);
    }

    public User queryByAccount(String account)
    {
        return userDao.queryAccount(account);
    }

    public User get(String id)
    {
        return userDao.get(id);
    }

    public void updateLoginTime()
    {
        User tmp = new User();
        tmp.setId(SessionUserUtil.getSessionUser().getId());
        tmp.setLastLoginTime(System.currentTimeMillis());
        userDao.update(tmp);
    }
}
